﻿using FlowCard.PrintCard.Helper;
using FlowCard.PrintCard.Models;
using Microsoft.Extensions.Options;
using OfficeOpenXml;

namespace FlowCard.PrintCard.Services
{
    /// <summary>
    /// 文件生成
    /// </summary>
    public class GenerateFile:IGenerateFile
    {
        private readonly ConstConfig config;
        public GenerateFile(ConstConfig config)
        {
            this.config = config;
        }

        public string GetorderPDF(Print print, string fileName = "生产订单流程卡")
        {
            var templatePath = config.PrintTempPdf;
            string path = config.PathPdf + Guid.NewGuid().ToString("N");
            if (print.PrintHeads == null || print.PrintHeads.Count == 0)
            {
                throw new ArgumentNullException("Printing header information does not exist");
            }
            //删除缓存文件，只保留三天的 
            DeleteOldFolders(config.PathPdf, 3);

            string fileNamepdf3 = $"{path}\\{fileName}(临时文件).pdf";
            string fileNamepdf4 = $"{path}\\{fileName}.pdf";


            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            foreach (var product in print.PrintHeads)
            {
                //二维码临时文件和路径
                string tempQRCodefoot = Guid.NewGuid().ToString("N") + "QRCode.png";
                string tempQRCodePath = $"{path}\\{tempQRCodefoot}";

                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                QRCodeHelper.CreateImage(product.ProcessCardNo, tempQRCodePath);

                string filerootName = path + "\\" + Guid.NewGuid().ToString("N");

                var packages = GeneratePdfPackage(print, product, templatePath, "", 11);

                var index = 1;
                packages.ForEach(package =>
                {
                    string tempFileName = filerootName + index.ToString() + ".xlsx";
                    //生成的Excel文件路径
                    string excelPath = Path.Combine(Directory.GetCurrentDirectory(), tempFileName);
                    var pdfPath = filerootName + index.ToString() + "_1.pdf";
                    package.SaveAs(new FileInfo(excelPath));

                    FileHelper.CovertoPdf(excelPath, pdfPath);
                    FileHelper.AddImgToPDF(pdfPath, filerootName + index.ToString() + ".pdf", tempQRCodePath, 90, 140, 485);
                    index++;
                });
            }

            string[] fileslist = Directory.GetFiles(path, "*.pdf")
                                          .OrderBy(file => new FileInfo(file).LastWriteTime)
                                          .ToArray(); ;

            FileHelper.MergePdf(fileslist.ToList(), fileNamepdf3);
            FileHelper.AddImgToPDF(fileNamepdf3, fileNamepdf4,config.ImagePath);
            // 删除文件夹内所有临时文件，只保留最终文件
            FileHelper.DeleteFile(path, fileNamepdf4);

            return fileNamepdf4;
        }
        public string GetorderPDFtwo(Print print, string fileName = "生产订单流程卡")
        {
            var templatePath = config.PrintTempPdfTwo;
            string path = config.PathPdfTwo + Guid.NewGuid().ToString("N");

            if (print.PrintHeads == null || print.PrintHeads.Count == 0)
            {
                throw new ArgumentNullException("Printing header information does not exist");
            }
            //删除缓存文件，只保留三天的
            DeleteOldFolders(config.PathPdfTwo, 3);

            string excelfileNamepdf2 = path + "\\" + Guid.NewGuid().ToString("N");
            string fileNamepdf3 = $"{path}\\{fileName}(临时文件).pdf";
            string fileNamepdf4 = $"{path}\\{fileName}.pdf";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            foreach (var head in print.PrintHeads)
            {
                //二维码临时文件和路径
                string tempQRCodefoot = Guid.NewGuid().ToString("N") + "QRCode.png";
                string tempQRCodePath = $"{path}\\{tempQRCodefoot}QRCode.png";

                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

                QRCodeHelper.CreateImage(head.ProcessCardNo, tempQRCodePath);


                string filerootName = path + "\\" + Guid.NewGuid().ToString("N");

                var packages = GeneratePdfPackageTwo(print, head, templatePath, "", 13);

                var index = 1;
                packages.ForEach(package =>
                {
                    string tempFileName = filerootName + index.ToString() + ".xlsx";
                    //生成的Excel文件路径
                    string filePath = Path.Combine(Directory.GetCurrentDirectory(), tempFileName);

                    package.SaveAs(new FileInfo(filePath));

                    FileHelper.CovertoPdf(filePath, filerootName + index.ToString() + "_1.pdf");
                    FileHelper.AddImgToPDF(filerootName + index.ToString() + "_1.pdf", filerootName + index.ToString() + ".pdf", tempQRCodePath, 90, 140, 485);

                    index++;
                });

            }

            string[] fileslist = Directory.GetFiles(path, "*.pdf")
                                          .OrderBy(file => new FileInfo(file).LastWriteTime)
                                          .ToArray(); ;

            FileHelper.MergePdf(fileslist.ToList(), fileNamepdf3);
            FileHelper.AddImgToPDF(fileNamepdf3, fileNamepdf4,config.ImagePath);
            // 删除文件夹内所有临时文件，只保留最终文件
            FileHelper.DeleteFile(path, fileNamepdf4);

            return fileNamepdf4;
        }
        public string GetorderExcel(Print print, string fileName = "MO")
        {
            var templatePath = config.PrintTempExcel;
            string path = config.PathExcel + Guid.NewGuid().ToString("N");

            if (print.PrintHeads == null || print.PrintHeads.Count == 0)
            {
                throw new ArgumentNullException("Printing header information does not exist");
            }
            string finalFile = $"{path}\\{fileName}.xlsx";
            //删除缓存文件，只保留3天的
            DeleteOldFolders(config.PathExcel, 3);

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var ecellist = new Dictionary<string, string>();

            foreach (var head in print.PrintHeads)
            {
                //二维码临时文件和路径
                string tempQRCodefoot = Guid.NewGuid().ToString("N") + "QRCode.png";
                string tempQRCodePath = $"{path}\\{tempQRCodefoot}";
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                //生成二维码
                QRCodeHelper.CreateImage(head.ProcessCardNo, tempQRCodePath);
                ecellist.Add(tempQRCodefoot, tempQRCodePath);
                var packages = GenerateExcelPackage(print, head, templatePath, tempQRCodePath, 0);
                var index = 1;
                packages.ForEach(package =>
                {
                    string filefloot = Guid.NewGuid().ToString("N") + "MO.xlsx";
                    string fileName = path + "\\" + filefloot;
                    //生成的Excel文件路径
                    string filePath = Path.Combine(Directory.GetCurrentDirectory(), fileName);

                    package.SaveAs(new FileInfo(filePath));
                    ecellist.Add($"{head.ProcessCardNo}{index}", filePath);
                    index++;
                });
            }

            // 将多个excel文件合并成一个
            FileHelper.MergeExcel(ecellist, finalFile);
            // 删除文件夹内所有临时文件，只保留最终文件
            FileHelper.DeleteFile(path, finalFile);
            return finalFile;
        }
        public string GetorderExcelTwo(Print print, string fileName = "MO")
        {
            var templatePath = config.PrintTempExcelTwo;
            string path = config.PathExcelTwo + Guid.NewGuid().ToString("N");

            if (print.PrintHeads == null || print.PrintHeads.Count == 0)
            {
                throw new ArgumentNullException("Printing header information does not exist");
            }
            var finalFile = $"{path}\\{fileName}.xlsx";
            //删除缓存文件，只保留3天的
            DeleteOldFolders(config.PathExcelTwo, 3);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var ecellist = new Dictionary<string, string>();

            foreach (var head in print.PrintHeads)
            {
                //二维码临时文件和路径
                string tempQRCodefoot = Guid.NewGuid().ToString("N") + "QRCode.png";
                string tempQRCodePath = $"{path}\\{tempQRCodefoot}";

                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

                //生成二维码
                QRCodeHelper.CreateImage(head.ProcessCardNo, tempQRCodePath);
                ecellist.Add(tempQRCodefoot, tempQRCodePath);
                var packages = GenerateExcelPackageTwo(print, head, templatePath, tempQRCodePath, 0);

                var index = 1;
                packages.ForEach(package =>
                {
                    string filefloot = Guid.NewGuid().ToString("N") + "MO.xlsx";
                    string fileName = path + "\\" + filefloot;
                    //生成的Excel文件路径
                    string filePath = Path.Combine(Directory.GetCurrentDirectory(), fileName);

                    package.SaveAs(new FileInfo(filePath));
                    ecellist.Add($"{head.ProcessCardNo}{index}", filePath);
                    index++;
                });
            }
            // 将多个excel文件合并成一个
            FileHelper.MergeExcel(ecellist, finalFile);
            // 删除文件夹内所有临时文件，只保留最终文件
            FileHelper.DeleteFile(path, finalFile);
            return finalFile;
        }
        public (FileStream fileStream, string contentType, string fileDownloadName) DownloadFile(string filepath)
        {
            // 检查文件是否存在
            if (!File.Exists(filepath))
            {
                throw new Exception("File not found.");
            }
            // 读取文件为流
            var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read);
            // 设置响应头
            var contentType = "application/octet-stream"; // 通用二进制流类型
            // 获取文件名（不含后缀）
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filepath);
            // 获取文件后缀
            string fileExtension = Path.GetExtension(filepath).TrimStart('.');
            var fileDownloadName = $"{fileNameWithoutExtension + "." + fileExtension}"; // 文件下载时的默认文件名
            return (fileStream, contentType, fileDownloadName);
        }


        #region 私有方法
        /// <summary>
        /// 删除过期文件，只保留有效期内的文件
        /// </summary>
        /// <param name="directoryPath">文件地址</param>
        /// <param name="daysOld">有效期</param>
        /// <returns></returns>
        private static bool DeleteOldFiles(string directoryPath, int daysOld)
        {
            if (!Directory.Exists(directoryPath))
            {
                Console.WriteLine("指定的目录不存在。");
                return false;
            }

            // 获取当前时间
            DateTime now = DateTime.Now;

            // 获取目录及其子目录下的所有文件
            string[] files = Directory.GetFiles(directoryPath, "*.*", SearchOption.AllDirectories);

            foreach (string file in files)
            {
                FileInfo fileInfo = new FileInfo(file);

                // 检查文件的创建时间是否超过指定天数
                if ((now - fileInfo.CreationTime).TotalDays > daysOld)
                {
                    try
                    {
                        // 删除临时文件
                        File.Delete(file);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 删除过期文件，永久删除，只保留有效期内的文件
        /// </summary>
        /// <param name="folderPath">文件夹地址</param>
        /// <param name="daysOld">有效期</param>
        /// <param name="Isdelete">是否删除，默认false</param>
        /// <returns></returns>
        private static bool DeleteOldFolders(string folderPath, int daysOld, bool Isdelete = false)
        {
            if (!Isdelete) { return false; }
            if (!Directory.Exists(folderPath))
            {
                return false;
            }
            //防止错误删除，最少保留一天的缓存文件
            if (daysOld == 0) { daysOld = 1; }


            DateTime currentTime = DateTime.Now;
            var subdirectories = Directory.GetDirectories(folderPath);

            foreach (var subdirectory in subdirectories)
            {
                var directoryInfo = new DirectoryInfo(subdirectory);
                DateTime creationTime = directoryInfo.CreationTime;

                if ((currentTime - creationTime).TotalDays > daysOld)
                {
                    Directory.Delete(subdirectory, true); // 删除文件夹及其内容
                }
            }

            return true;
        }

        /// <summary>
        /// 零件生成pdf 的excel
        /// </summary>
        /// <param name="print"></param>
        /// <param name="head"></param>
        /// <param name="templatePath"></param>
        /// <param name="tempQRCodePath"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        private static List<ExcelPackage> GeneratePdfPackage(Print print, PrintHead head, string templatePath, string tempQRCodePath, int pageSize = 11, int startRow = 14)
        {
            var packages = new List<ExcelPackage>();

            var index = 0;
            // 使用拉姆达表达式查询和排序

            var data = new List<PrintHeadItem>();
            if (head.Items != null && head.Items.Count > 0)
            {
                data = head.Items // 过滤条件
                .OrderBy(p => p.ProcessNumber)// 排序条件
                .ToList();
            }
            var count = data.Count == 0 ? 1 : data.Count;
            if (pageSize == 0) { pageSize = count; }
            var pageCount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;// var pageCount = count / pageSize;
            if (pageCount == 0)
            {
                // 最少1页，没有数据打印空页
                pageCount = 1;
            }

            for (int i = 0; i < pageCount; i++)
            {
                var package = new ExcelPackage(new FileInfo(templatePath));
                //设置表头
                var worksheet = package.Workbook.Worksheets[0];
                worksheet.Cells["E1"].Value = print.ProcessCardName;
                //worksheet.Cells["K3"].Value = print.PrintName;
                worksheet.Cells["B7"].Value = "格式编号：" + print.FormatCode;
                // worksheet.Cells["K2"].Value = "第" + (i + 1).ToString() + "页   共" + k.ToString() + "页";
                worksheet.Cells["K25"].Value = $@"打印人:{print.PrintName}  第{i + 1}页/共{pageCount}页";

                worksheet.Cells["A10"].Value = head.ProjectCode;
                worksheet.Cells["C10"].Value = head.ProductCode;
                worksheet.Cells["E10"].Value = head.PartDrawingNo;
                worksheet.Cells["F10"].Value = head.PartName;
                worksheet.Cells["I10"].Value = head.ProdBatch;
                worksheet.Cells["K10"].Value = head.ProdQuantity;
                worksheet.Cells["L10"].Value = head.StartDate;
                worksheet.Cells["B11"].Value = head.MaterialCode;
                worksheet.Cells["D11"].Value = head.MaterialName;
                worksheet.Cells["G11"].Value = head.MaterialBatchNo;
                worksheet.Cells["J11"].Value = head.MaterialSpec;
                worksheet.Cells["M11"].Value = head.PartsManufacturable;
                worksheet.Cells["E7"].Value = "料品编号：" + head.MaterialItemNo;
                worksheet.Cells["K7"].Value = "流程卡号：" + head.ProcessCardNo;

                for (int j = 0; j < pageSize && index <= data.Count - 1; j++)
                {
                    worksheet.Cells[startRow + j, 1].Value = data[index].ProcessNumber;
                    worksheet.Cells[startRow + j, 2].Value = data[index].ProcessName;
                    worksheet.Cells[startRow + j, 3].Value = data[index].WorkcenterName;
                    index++;
                }
                if (!string.IsNullOrEmpty(tempQRCodePath))
                {
                    /// 将二维码添加到表格
                    using (var fileinfo = new FileStream(tempQRCodePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        var picture = worksheet.Drawings.AddPicture("QRCodeImg", fileinfo);
                        // 设置二维码的大小
                        picture.SetSize(120, 120);
                        picture.LockAspectRatio = true; // 如果库支持此属性
                                                        // 将图片定位到 A1 单元格
                                                        // 行偏移量为 0 列偏移量为 0，即 A1 单元格
                        picture.SetPosition(0, 0, 2, 0);
                    }
                }

                packages.Add(package);
            }

            return packages;
        }
        /// <summary>
        /// 部整件生成pdf的excel
        /// </summary>
        /// <param name="print"></param>
        /// <param name="head"></param>
        /// <param name="templatePath"></param>
        /// <param name="tempQRCodePath"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        private static List<ExcelPackage> GeneratePdfPackageTwo(Print print, PrintHead head, string templatePath, string tempQRCodePath, int pageSize = 11, int startRow = 13)
        {
            var packages = new List<ExcelPackage>();

            var index = 0;
            // 使用拉姆达表达式查询和排序
            var data = new List<PrintHeadItem>();
            if (head.Items != null && head.Items.Count > 0)
            {
                data = head.Items // 过滤条件
                .OrderBy(p => p.ProcessNumber)// 排序条件
                .ToList();
            }
            var count = data.Count == 0 ? 1 : data.Count;
            if (pageSize == 0) { pageSize = count; }
            var pageCount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1; //count / pageSize;
            if (pageCount == 0)
            {
                // 最少1页，没有数据打印空页
                pageCount = 1;
            }

            for (int i = 0; i < pageCount; i++)
            {
                var package = new ExcelPackage(new FileInfo(templatePath));
                //设置表头
                var worksheet = package.Workbook.Worksheets[0];
                worksheet.Cells["E1"].Value = print.ProcessCardName;
                //worksheet.Cells["K3"].Value = print.PrintName;
                worksheet.Cells["A7"].Value = "格式编号：" + print.FormatCode;
                worksheet.Cells["K26"].Value = $@"打印人:{print.PrintName}  第{i + 1}页/共{pageCount}页";

                worksheet.Cells["A10"].Value = head.ProductCode;
                worksheet.Cells["E10"].Value = head.PartDrawingNo;
                worksheet.Cells["F10"].Value = head.PartName;
                worksheet.Cells["I10"].Value = head.ProdBatch;
                worksheet.Cells["K10"].Value = head.ProdQuantity;
                worksheet.Cells["E7"].Value = "料品编号：" + head.MaterialItemNo;
                worksheet.Cells["K7"].Value = "流程卡号：" + head.ProcessCardNo;


                for (int j = 0; j < pageSize && index <= data.Count - 1; j++)
                {
                    worksheet.Cells[startRow + j, 1].Value = data[index].ProcessNumber;
                    worksheet.Cells[startRow + j, 2].Value = data[index].ProcessName;
                    worksheet.Cells[startRow + j, 3].Value = data[index].WorkcenterName;
                    index++;
                }
                if (!string.IsNullOrEmpty(tempQRCodePath))
                {
                    using (var fileinfo = new FileStream(tempQRCodePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        var picture = worksheet.Drawings.AddPicture("QRCodeImg", fileinfo);
                        // 设置二维码的大小
                        picture.SetSize(120, 120);
                        picture.LockAspectRatio = true; // 如果库支持此属性
                                                        // 将图片定位到 A1 单元格
                                                        // 行偏移量为 0 列偏移量为 0，即 A1 单元格
                        picture.SetPosition(0, 0, 2, 0);
                    }
                }

                packages.Add(package);
            }

            return packages;
        }
        /// <summary>
        /// 零件生成excel，每个sheet一个订单
        /// </summary>
        /// <param name="print"></param>
        /// <param name="head"></param>
        /// <param name="templatePath"></param>
        /// <param name="tempQRCodePath"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        private static List<ExcelPackage> GenerateExcelPackage(Print print, PrintHead head, string templatePath, string tempQRCodePath, int pageSize = 11, int startRow = 14)
        {
            var packages = new List<ExcelPackage>();

            var index = 0;
            // 使用拉姆达表达式查询和排序
            var data = new List<PrintHeadItem>();
            if (head.Items != null && head.Items.Count > 0)
            {
                data = head.Items // 过滤条件
                .OrderBy(p => p.ProcessNumber)// 排序条件
                .ToList();
            }
            var count = data.Count == 0 ? 1 : data.Count;
            if (pageSize == 0) { pageSize = count; }
            var pageCount = count / pageSize;
            if (pageCount == 0)
            {
                // 最少1页，没有数据打印空页
                pageCount = 1;
            }

            for (int i = 0; i < pageCount; i++)
            {
                var package = new ExcelPackage(new FileInfo(templatePath));
                //设置表头
                var worksheet = package.Workbook.Worksheets[0];
                worksheet.Cells["E1"].Value = print.ProcessCardName;
                worksheet.Cells["K3"].Value = "打印人：" + print.PrintName;
                worksheet.Cells["A7"].Value = "格式编号：" + print.FormatCode;

                worksheet.Cells["A10"].Value = head.ProjectCode;
                worksheet.Cells["C10"].Value = head.ProductCode;
                worksheet.Cells["E10"].Value = head.PartDrawingNo;
                worksheet.Cells["F10"].Value = head.PartName;
                worksheet.Cells["I10"].Value = head.ProdBatch;
                worksheet.Cells["K10"].Value = head.ProdQuantity;
                worksheet.Cells["L10"].Value = head.StartDate;
                worksheet.Cells["B11"].Value = head.MaterialCode;
                worksheet.Cells["D11"].Value = head.MaterialName;
                worksheet.Cells["G11"].Value = head.MaterialBatchNo;
                worksheet.Cells["J11"].Value = head.MaterialSpec;
                worksheet.Cells["M11"].Value = head.PartsManufacturable;
                worksheet.Cells["E7"].Value = "料品编号："+head.MaterialItemNo;
                worksheet.Cells["K7"].Value = "流程卡号：" + head.ProcessCardNo;

                for (int j = 0; j < pageSize && index <= data.Count - 1; j++)
                {
                    worksheet.Cells[startRow + j, 1].Value = data[index].ProcessNumber;
                    worksheet.Cells[startRow + j, 2].Value = data[index].ProcessName;
                    worksheet.Cells[startRow + j, 3].Value = data[index].WorkcenterName;
                    index++;
                }
                if (!string.IsNullOrEmpty(tempQRCodePath))
                {
                    using (var fileinfo = new FileStream(tempQRCodePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        var picture = worksheet.Drawings.AddPicture("QRCodeImg", fileinfo);
                        // 设置二维码的大小
                        picture.SetSize(120, 120);
                        picture.LockAspectRatio = true; // 如果库支持此属性
                                                        // 将图片定位到 A1 单元格
                                                        // 行偏移量为 0 列偏移量为 0，即 A1 单元格
                        picture.SetPosition(0, 0, 2, 0);
                    }
                }
                packages.Add(package);
            }

            return packages;
        }
        /// <summary>
        /// 生成部件Excel，每个sheet一个订单
        /// </summary>
        /// <param name="print"></param>
        /// <param name="head"></param>
        /// <param name="templatePath"></param>
        /// <param name="tempQRCodePath"></param>
        /// <param name="pageSize"></param>
        /// <param name="startRow"></param>
        /// <returns></returns>
        private static List<ExcelPackage> GenerateExcelPackageTwo(Print print, PrintHead head, string templatePath, string tempQRCodePath, int pageSize = 11, int startRow = 13)
        {
            var packages = new List<ExcelPackage>();

            var index = 0;
            // 使用拉姆达表达式查询和排序
            var data = new List<PrintHeadItem>();
            if (head.Items != null && head.Items.Count > 0)
            {
                data = head.Items // 过滤条件
                .OrderBy(p => p.ProcessNumber)// 排序条件
                .ToList();
            }
            var count = data.Count == 0 ? 1 : data.Count;
            if (pageSize == 0) { pageSize = count; }
            var pageCount = count / pageSize;
            if (pageCount == 0)
            {
                // 最少1页，没有数据打印空页
                pageCount = 1;
            }

            for (int i = 0; i < pageCount; i++)
            {
                var package = new ExcelPackage(new FileInfo(templatePath));
                //设置表头
                var worksheet = package.Workbook.Worksheets[0];
                worksheet.Cells["E1"].Value = print.ProcessCardName;
                worksheet.Cells["K3"].Value = "打印人：" + print.PrintName;
                worksheet.Cells["A7"].Value = "格式编号：" + print.FormatCode;

                worksheet.Cells["C10"].Value = head.ProductCode;
                worksheet.Cells["E10"].Value = head.PartDrawingNo;
                worksheet.Cells["F10"].Value = head.PartName;
                worksheet.Cells["I10"].Value = head.ProdBatch;
                worksheet.Cells["K10"].Value = head.ProdQuantity;
                worksheet.Cells["E7"].Value = "料品编号：" + head.MaterialItemNo;
                worksheet.Cells["K7"].Value = "流程卡号：" + head.ProcessCardNo;

                for (int j = 0; j < pageSize && index <= data.Count - 1; j++)
                {
                    worksheet.Cells[startRow + j, 1].Value = data[index].ProcessNumber;
                    worksheet.Cells[startRow + j, 2].Value = data[index].ProcessName;
                    worksheet.Cells[startRow + j, 3].Value = data[index].WorkcenterName;
                    index++;
                }
                if (!string.IsNullOrEmpty(tempQRCodePath))
                {
                    using (var fileinfo = new FileStream(tempQRCodePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        var picture = worksheet.Drawings.AddPicture("QRCodeImg", fileinfo);
                        // 设置二维码的大小
                        picture.SetSize(120, 120);
                        picture.LockAspectRatio = true; // 如果库支持此属性
                                                        // 将图片定位到 A1 单元格
                                                        // 行偏移量为 0 列偏移量为 0，即 A1 单元格
                        picture.SetPosition(0, 0, 2, 0);
                    }
                }
                packages.Add(package);
            }

            return packages;
        }
        #endregion
    }
}
